#!/bin/bash


#
#@copyright Copyright (c) 2025 CSG Digital Grid Technology (Guangdong) Co., Ltd.
#@author Huang  Jiaqi
#



GREEN='\033[0;32m' # 绿色
YELLOW='\033[33m'  # 黄色
RED='\e[31m'       # 红色
NC='\033[0m'       # 重置颜色

appm="PES_appm_v1_241218"
# echo -e "${GREEN}$appm${NC}"
# sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1测试1112/" $guanjia 2>/dev/null
# 创建必要文件夹
folders=(
    "/userdata/tmp"
	"/userdata/tmp/hash"
	"/userdata/tmp/hash/x86_64"
	"/userdata/tmp/hash/aarch64"
    "/userdata/data"
    "/userdata/log"
    "/userdata/version"
	"/PowerHarmony/SMC/download/"
)

for folder in "${folders[@]}"; do
    if [ ! -d "$folder" ]; then
        mkdir -p "$folder"
        echo "Created folder: $folder"
    fi
done


# 创建必要文件
files=(
    "/userdata/log/log.txt"
	"/userdata/log/guanjia.txt"
)

for file in "${files[@]}"; do
    if [ ! -e $file ]; then
        touch $file
        echo "Created file: $file"
    fi
done


# 文件夹以及文件变量
data_tmp_dir="/userdata/tmp/"
data_hash_x86="/userdata/tmp/hash/x86_64"
data_hash_aarch64="/userdata/tmp/hash/aarch64"
data_package_dir="/userdata/tmp/*/package"
data_version_file="/userdata/tmp/*/.version"
data_start_file="/userdata/tmp/*/start.sh"
data_dir="/userdata/data"
data_version_dir="/userdata/version"
log_dir="/userdata/log"
log_file="/userdata/log/log.txt"
templog_file="/userdata/log/temp.log"
checklog_file="/userdata/log/check.log"
hashlog_file="/userdata/log/hash.log"
guanjia="/userdata/log/guanjia.txt"

tmp_dir="/PowerHarmony/SMC/download"
package_dir="/PowerHarmony/SMC/download/*/package"
version_file="/PowerHarmony/SMC/download/*/.version"
start_file="/PowerHarmony/SMC/download/*/start.sh"

time=$(date "+%Y-%m-%d %H:%M:%S")
et=$(date +"%Y%m%d%H%M%S%3N")




# dian函数
dian() {
clear_line() {
    printf "\r%s\r" "$(tput el)"
}
chars=('' '.' '..' '...' '....' '.....' '......')
count=0
while [ $count -lt 1 ]; do
    for char in "${chars[@]}"; do
     #   printf "%s" "$char"
		 printf "\r正在验签,请稍候%s" "$char"
        sleep 0.3
        clear_line
    done
    ((count++))
done
}


dian_1() {
clear_line() {
    printf "\r%s\r" "$(tput el)"
}
chars=('' '.' '..' '...' '....' '.....' '......')
count=0
while [ $count -lt 1 ]; do
    for char in "${chars[@]}"; do
     #   printf "%s" "$char" 
		 printf "\r正在验证安装包,请稍候%s" "$char"
        sleep 0.3
        clear_line
    done
    ((count++))
done
}

##################################################### 验签 ###############################################################




check() {

log_file="/userdata/log/log.txt"
checklog_file="/userdata/log/check.log"
guanjia="/userdata/log/guanjia.txt"
> $checklog_file
 # dian &
 # dian_pid=$!

# 初始化标志变量
signature_error=false
version_hash=false
# 哈希错误文件列表
invalid_files=()


# 计算文件的 sha256 哈希值并比较
for fileha in ${package_dir}/*; do
    if [ -f "$fileha" ]; then
        # 计算文件的 sha256 哈希值并比较
        hash=$(sha256sum "$fileha" | awk '{print $1}')
        # 检查当前文件的哈希值是否在 .version 中
        if ! grep -qFx "$hash" ${version_file}; then
            signature_error=true 
			version_hash=true
			# 记录无效文件
			 invalid_files+=("$fileha")
			# invalid_files+=("$hash")
			# invalid_files+=("$fileha:$hash")
			
        fi
    fi
done


# 检查 start.sh 文件夹
if [ ! -f ${start_file} ]; then

	echo -e "${RED}Sign check error:${NC} start.sh 文件异常" >> $checklog_file
	echo "$(date "+%Y-%m-%d %H:%M:%S") 验签异常：start.sh 文件异常" >> $log_file
	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1start.sh 文件异常/" $guanjia 2>/dev/null
	cat $checklog_file
	exit 1
fi

# 检查 package 文件夹
if [ ! -d ${package_dir} ]; then

	echo -e "${RED}Sign check error:${NC} package 文件夹异常" >> $checklog_file
	echo "$(date "+%Y-%m-%d %H:%M:%S") 验签异常：package 文件夹异常" >> $log_file
	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1package 文件夹异常/" $guanjia 2>/dev/null
	cat $checklog_file
	exit 1
fi

# 检查 .version 文件
if [ ! -f ${version_file} ]; then

	echo -e "${RED}Sign check error:${NC} version 信息异常" >> $checklog_file
	echo "$(date "+%Y-%m-%d %H:%M:%S") 验签异常：version 文件异常" >> $log_file
	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1version 文件异常/" $guanjia 2>/dev/null
	cat $checklog_file
	exit 1
fi

# # version字段检查
# fields=("应用名称" "系统版本" "应用架构" "应用来源" "应用版本号" "应用所需容量" "应用所需内存" "应用所需核数" "应用所需线程数")
# for field in "${fields[@]}"; do
	# if grep -q "$field" ${version_file}; then
		# echo "$(date "+%Y-%m-%d %H:%M:%S") version 字段齐全" >> $log_file
	# else				
		# echo -e "${RED}Sign check error:${NC} version 文件缺少字段: $field" >> $checklog_file
		# echo -e "${RED}Sign check error:${NC} version 文件缺少字段: $field" >> $log_file
		# cat $checklog_file
		# exit 1
	
	
	# fi
# done

		# 应用架构判断
		app_arch1=$(grep "应用名称" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch1" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用名称参数异常" >> $checklog_file ;sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用名称参数异常/" $guanjia 2>/dev/null ;fi
		
		app_arch4=$(grep "应用来源" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch4" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用来源参数异常" >> $checklog_file ;sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用来源参数异常/" $guanjia 2>/dev/null ;fi
		
		app_arch5=$(grep "应用版本号" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch5" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用版本号参数异常" >> $checklog_file ;sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用版本号参数异常/" $guanjia 2>/dev/null ;fi
		
		app_arch8=$(grep "应用所需核数" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch8" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用所需核数参数异常" >> $checklog_file ;fsed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用所需核数参数异常/" $guanjia 2>/dev/null ;fi
		
		app_arch9=$(grep "应用所需线程数" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch9" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用所需线程数参数异常" >> $checklog_file ;sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用所需线程数参数异常/" $guanjia 2>/dev/null ;fi

		
		# 判定应用所需容量，根目录需要2倍于应用
		app_arch6=$(grep "应用所需容量" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch6" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用所需容量参数异常" >> $checklog_file ;sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用所需容量参数异常/" $guanjia 2>/dev/null
		else
			disk_size=$(df -BM / | awk 'NR==2{print $4}' | sed 's/M//')
			d_size=$(echo $app_arch6 | sed 's/ MB//')
			required_size=$(( $d_size * 2 )) > /dev/null 2>&1
			echo "$(date "+%Y-%m-%d %H:%M:%S") " >> $log_file
			echo "$(date "+%Y-%m-%d %H:%M:%S") 应用所需容量 $required_size M" >> $log_file
			echo "$(date "+%Y-%m-%d %H:%M:%S") 当前/容量 $disk_size M" >> $log_file
			if [ $required_size -gt $disk_size ]; then
				signature_error=true
				echo -e "${RED}Sign check error:${NC} 根目录空间不足" >> $checklog_file
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1根目录空间不足/" $guanjia 2>/dev/null
			fi
		fi

		# 判定应用所需内存
		app_arch7=$(grep "应用所需内存" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch7" ]; then signature_error=true; echo -e "${RED}Sign check error:${NC} 应用所需内存参数异常" >> $checklog_file; sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用所需内存参数异常/" $guanjia 2>/dev/null
		else
			mem_size=$(free -m |grep Mem |awk {' print $2 '})
			m_size=$(echo $app_arch7 | sed 's/ MB//')
			mrequired_size=$(( $m_size * 1 ))
			echo "$(date "+%Y-%m-%d %H:%M:%S") 应用所需内存 $mrequired_size M" >> $log_file
			echo "$(date "+%Y-%m-%d %H:%M:%S") 当前内存 $mem_size M" >> $log_file
			if [ $mrequired_size -gt $mem_size ]; then
				signature_error=true
				echo -e "${RED}Sign check error:${NC} 设备内存不足" >> $checklog_file
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1设备内存不足/" $guanjia 2>/dev/null
			fi
		fi	

		
		# 获取系统版本信息
		system_info=$(uname -a)
		system_info_r=$(uname -r)
		

		


		app_arch3=$(grep "应用架构" ${version_file} | awk -F "：" '{print $2}')
		if [ -z "$app_arch3" ]; then signature_error=true;echo "" >> $checklog_file ; echo -e "${RED}Sign check error:${NC} 应用架构参数异常" >> $checklog_file; sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用架构参数异常/" $guanjia 2>/dev/null ;fi
		
		# 应用架构判断提取的参数中是否包含x86或者aarch64关键字
		if [[ ! ($app_arch3 == *"x86"* || $app_arch3 == *"aarch64"*) ]]; then 
			signature_error=true
			echo -e "${RED}Sign check error:${NC} 应用架构参数中不包含x86或aarch64" >> $checklog_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用架构参数中不包含x86或aarch64/" $guanjia 2>/dev/null
		fi

		# 获取系统架构信息
		system_info_m=$(uname -m)

		# 检查系统架构是否包含应用架构
		if [[ "$system_info_m" == *"$app_arch3"* ]]; then
			echo "$(date "+%Y-%m-%d %H:%M:%S") 当前系统架构为: $system_info_m" >> $log_file
		else
			signature_error=true
	#		echo "" >> $checklog_file
			echo -e "${RED}Sign check error:${NC} 当前系统架构为: $system_info_m 应用支持架构为: $app_arch3" >> $checklog_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1当前系统架构为: $system_info_m 应用支持架构为: $app_arch3/" $guanjia 2>/dev/null
	#		echo -e "${RED}Sign check error:${NC} 应用支持架构为: $app_arch3" >> $checklog_file
		fi	
		
		


}


##################################################### 判断安装类型 #######################################################


i_type() {
# 使用find命令查找目录下的所有文件和文件夹

if [ "$type" = "install" ]; then
        items=$(find ${package_dir} -mindepth 1)
		
elif [ "$type" = "uninstall" ]; then
	rpm_folder="$data_dir/$PATTERN/package"
	# 判断文件夹是否存在
	if [ ! -d "$rpm_folder" ]; then
		echo "uninstall_file_error"
		exit 1
	fi
			
        items=$(find "$data_dir/$PATTERN/package" -mindepth 1)
else
        echo "执行类型异常"

fi


# 文件夹/userdata/tmp/*/package目录里预设3种文件，
# 名字带.rpm的文件，名字不带.rpm的文件，文件夹
# 用于记录是否存在文件夹
has_folder=false

# 用于记录是否存在名字带.rpm的文件
has_rpm=false

# 用于记录是否存在名字不带.rpm的文件
has_not_rpm=false

# 遍历查找到的所有项
for item in $items; do
    if [ -d $item ]; then
        has_folder=true
    elif [[ $item == *.rpm ]]; then
        has_rpm=true
    elif [[ $item != *.rpm ]]; then
        has_not_rpm=true
    fi
done

if [ -z "$items" ]; then
    echo "i_type_err"
    exit 1
fi

# 文件夹/userdata/tmp/*/package目录里预设3种文件，
# 名字带.rpm的文件，名字不带.rpm的文件，文件夹

# 如果包含有文件、文件夹以及rpm包，则输出文件类型异常
# 如果包含有文件以及rpm包，则输出文件类型异常
# 如果全是有文件夹以及rpm包，则输出文件类型异常

# 如果全是名字带.rpm的文件则执行rpmm函数
# 如果没有名字带.rpm的文件且有文件夹则执行cpp函数
# 如果没有名字带.rpm的文件且有文件夹和文件则执行cpp函数

if $has_folder && $has_rpm && $has_not_rpm; then
echo "$(date "+%Y-%m-%d %H:%M:%S") 有文件、文件夹以及rpm包" >> $log_file
#    echo "有文件、文件夹以及rpm包"
    echo "i_type_err"
	
elif $has_not_rpm && $has_rpm; then
echo "$(date "+%Y-%m-%d %H:%M:%S") 有文件以及rpm包" >> $log_file
#    echo "有文件以及rpm包"
    echo "i_type_err"
	
elif $has_folder && $has_rpm; then
echo "$(date "+%Y-%m-%d %H:%M:%S") 有文件夹以及rpm包" >> $log_file
#    echo "有文件夹以及rpm包"
    echo "i_type_err"
	
elif $has_rpm &&! $has_folder &&! $has_not_rpm; then
echo "$(date "+%Y-%m-%d %H:%M:%S") rpmm" >> $log_file
    echo "rpmm"
	
elif ! $has_rpm && $has_folder; then
echo "$(date "+%Y-%m-%d %H:%M:%S") cpp" >> $log_file
    echo "cpp"
	
elif ! $has_rpm && $has_not_rpm; then
echo "$(date "+%Y-%m-%d %H:%M:%S") cpp" >> $log_file	
	echo "cpp"
	
	fi
	
}


##################################################### 解析参数 #####################################################


# 显示使用说明
function usage {
    echo "Usage: appm -i -p <path>             # Install"
    echo "       appm -u -n <apply name>       # Uninstall"
    echo "       appm -c                       # Installation status"
    echo "       appm -V                       # Installed application version information"
    echo "       appm -V -n <apply name>       # Application Information"	
    echo "       appm -l                       # Installed application status information"
    echo "       appm -l -n <apply name>       # Application status information"
    echo "       appm -v                       # Appm version information"
    exit 1
}

if [ "$#" -lt 1 ]; then
    usage
fi

# 初始化标志变量
V_flag=0
l_flag=0

while getopts ":iup:n:clVv" opt; do
    case ${opt} in
        i )
            INSTALL=1
            ;;
        u )
            UNINSTALL=1
            FILENAME="$OPTARG"
            ;;
        p )
            PATH_OR_FILE="$OPTARG"
            ;;
        n )
            PATTERN="$OPTARG"
            ;;
        c )
			# if [ -f $tmp_dir/*/*_upgradeStatus.ini ]; then
				# tail -n 20 -f $tmp_dir/*/*_upgradeStatus.ini
			# else
				# echo "当前无应用在安装"
			# fi
			 # exit 0
			status_file_c=$tmp_dir/*_upgradeStatus.ini
			if [ -f $tmp_dir/*_upgradeStatus.ini ]; then
				tail -n 20 -f $tmp_dir/*_upgradeStatus.ini
				echo $tmp_dir/*_upgradeStatus.ini
			else
				echo "当前无应用在安装"
			fi
			 exit 0
            ;;
        V )
            V_flag=1
            ;;
        l )
            l_flag=1
            ;;
		v )
			echo ""
			echo -e "${GREEN}$appm${NC}"
            echo ""
			exit 0
			
            ;;	
        \? )
            usage
            ;;
    esac
done


##################################################### 安装或复制功能 #####################################################


if [ "$INSTALL" ] && [ -n "$PATH_OR_FILE" ]; then
	echo -e "${GREEN}$appm${NC}"
	echo "" >> $log_file
	echo "$appm" >> $log_file
	echo "$(date "+%Y-%m-%d %H:%M:%S")" >> $log_file
	echo "$(date "+%Y-%m-%d %H:%M:%S") 安装 $PATH_OR_FILE" >> $log_file
	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1安装 $PATH_OR_FILE/" $guanjia 2>/dev/null
	echo ""
	echo "应用安装开始"
	echo ""

	#	先清除/tmp_dir下的文件
	#	rm -rf $tmp_dir/*
		find "$tmp_dir" -mindepth 1 -type d -exec rm -r {} + > /dev/null 2>&1
		rm -rf $tmp_dir/*_upgradeStatus.ini
		tar -xzvf $PATH_OR_FILE -C $tmp_dir 2>> $log_file 
	
		# 获取解压后的文件夹名称
		extracted_folder=$(find "$tmp_dir" -mindepth 1 -maxdepth 1 -type d)
		# 在解压后的文件夹里创建文件
#		status_file="$extracted_folder/$(basename "$PATH_OR_FILE")_upgradeStatus.ini"
		status_file="$tmp_dir/$(basename "$PATH_OR_FILE")_upgradeStatus.ini"
		touch "$status_file"
	
	
	# 判断1
	if [[ $PATH_OR_FILE == *.tar.gz ]]; then

		echo ""
		dian_1 &
		dian_1_pid=$!
		wait $dian_1_pid
		
		
		# 检查 .version 文件
		if [ ! -f ${version_file} ]; then
			echo ""
			echo -e "${RED}error:${NC} 应用 version 信息异常"
			echo "$(date "+%Y-%m-%d %H:%M:%S") error: 应用 version 信息异常" >> $log_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用 version 信息异常/" $guanjia 2>/dev/null
			echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
			exit 1
		fi
		
		# 检查 start.sh 文件夹
		if [ ! -f ${start_file} ]; then
			echo ""
			echo -e "${RED}error:${NC} start.sh 文件异常"
			echo "$(date "+%Y-%m-%d %H:%M:%S") error：start.sh 文件异常" >> $log_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1start.sh 文件异常/" $guanjia 2>/dev/null
			echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
			exit 1
		fi

		# 检查 package 文件夹
		if [ ! -d ${package_dir} ]; then
			echo ""
			echo -e "${RED}error:${NC} package 文件夹异常"
			echo "$(date "+%Y-%m-%d %H:%M:%S") error：package 文件夹异常" >> $log_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1package 文件夹异常/" $guanjia 2>/dev/null
			echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file			
			exit 1
		fi


		echo "应用详情："
		head -n 11  ${version_file}
		head -n 11 ${version_file} | sed "s/^/$(date "+%Y-%m-%d %H:%M:%S") /" >> $log_file
		# version字段检查
		fields=("应用名称" "系统版本" "应用架构" "应用来源" "应用版本号" "应用所需容量" "应用所需内存" "应用所需核数" "应用所需线程数")
		for field in "${fields[@]}"; do
			if grep -q "$field" ${version_file}; then
				
				echo "$(date "+%Y-%m-%d %H:%M:%S") version $field 字段齐全" >> $log_file
			else
				echo ""
				echo -e "${RED}error:${NC} version 文件缺少字段: $field"
				echo "$(date "+%Y-%m-%d %H:%M:%S") version 文件缺少字段: $field" >> $log_file
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1version 文件缺少字段: $field/" $guanjia 2>/dev/null
				echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
				exit 1
			fi
		done
		echo ""

		echo "安装包验证通过"
		sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1安装包验证通/" $guanjia 2>/dev/null
		
		
		
			
		
		# # 获取解压后的文件夹名称
		# extracted_folder=$(find "$tmp_dir" -mindepth 1 -maxdepth 1 -type d)
		# # 在解压后的文件夹里创建文件
		# status_file="$extracted_folder/$(basename "$PATH_OR_FILE")_upgradeStatus.ini"
		# touch "$status_file"
		
		
		# 验签
		echo ""
		dian &
		dian_pid=$!
		wait $dian_pid
		check


# version_hash=true
		if [ "$signature_error" = "true" ] && [ "$version_hash" = "true" ]; then
			echo -e "${RED}Sign check error:${NC} 哈希值验证异常" >> $checklog_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1哈希值验证异常/" $guanjia 2>/dev/null
			echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
		fi

		if $signature_error; then
		
			
			
			echo ""
			echo -e "${RED}Sign check error:${NC} 验签失败"
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1验签失败/" $guanjia 2>/dev/null
			echo ""
			cat $checklog_file
			echo ""
			

			
			sed "s/^/$(date "+%Y-%m-%d %H:%M:%S") /" $checklog_file >> $log_file
			
				for invalid_file in "${invalid_files[@]}"; do
					echo "$(date "+%Y-%m-%d %H:%M:%S") $invalid_file" >> $log_file
				done
				
			echo "$(date "+%Y-%m-%d %H:%M:%S") error: 验签失败" >> $log_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1验签失败/" $guanjia 2>/dev/null
			echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
			exit 1

		else
			echo "验签通过"
			echo "$(date "+%Y-%m-%d %H:%M:%S") 验签通过" >> $log_file
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1验签通过/" $guanjia 2>/dev/null

		fi
		sleep 1
		
		
		# 判断i_type输出
		type="install"
		i_output=$(i_type)
		
		
			#rpmm包安装
			if [[ "$i_output" == *"rpmm"* ]]; then
				echo ""
			#	echo "rpmmmmm"
				echo "$(date "+%Y-%m-%d %H:%M:%S") rpmmmmm" >> $log_file
				echo "$(date +"%Y%m%d%H%M%S%3N"):101" >> $status_file
				echo "$(date +"%Y%m%d%H%M%S%3N"):103" >> $status_file
				
				# 获取 RPM 包的总数量
				rpm_files=($(find ${package_dir} -maxdepth 1 -type f -name "*.rpm"))
				total_rpms=${#rpm_files[@]}  # RPM 包的总数
				current_progress=0  # 当前进度
				output_progress_90=false  # 是否已输出90%的标志
				
				
				# 如果 RPM 包的总数大于 0，则开始安装
				if [ $total_rpms -gt 0 ]; then
					echo "总共有 $total_rpms 个 RPM 包，开始安装..."
					echo ""
					echo "安装进度: 0%"
					echo "$(date +"%Y%m%d%H%M%S%3N"):105&0" >> $status_file
					# 在每次安装前先清空临时日志文件
					> "$templog_file"

					#所有输出不输出并重定向到日志文件		
				#	rpm -Uvh --force ${package_dir}/* > >(tee -a "$templog_file" "$log_file" > /dev/null) 2>&1 & 
					#只输出错误信息且并重定向到日志文件
					rpm -Uvh --force ${package_dir}/* > >(tee -a "$templog_file" >> "$log_file") 2> >(tee -a "$templog_file" "$log_file" >&2) &

					pid=$!  # 获取安装进程的 PID

					# 监控临时文件以计算进度

					while kill -0 $pid 2>/dev/null; do
					sleep 0.05  # 每 0.05 秒检查一次进度

					# 计算进度标记出现的次数grep
					progress_count=$(grep -c "##################################" "$templog_file")
					progress=$((progress_count * 100 / total_rpms))  # 计算百分比进度
					
						# 检查是否需要输出进度
					if [ $progress -gt $current_progress ]; then # 根据进度范围输出相应的进度
					
						if [ $progress -lt 10 ]; then output_progress=10
							elif [ $progress -lt 20 ]; then output_progress=20
							elif [ $progress -lt 30 ]; then output_progress=30
							elif [ $progress -lt 40 ]; then output_progress=40
							elif [ $progress -lt 50 ]; then output_progress=50
							elif [ $progress -lt 60 ]; then output_progress=60
							elif [ $progress -lt 70 ]; then output_progress=70
							elif [ $progress -lt 80 ]; then output_progress=80
							elif [ $progress -lt 90 ]; then output_progress=90
						fi

						# 只在当前进度小于输出进度时输出
						if [ $current_progress -lt $output_progress ]; then
							echo "安装进度: $output_progress%"
							echo "$(date +"%Y%m%d%H%M%S%3N"):105&$output_progress" >> $status_file 
							echo "$(date "+%Y-%m-%d %H:%M:%S") 安装进度: $output_progress%" >> $log_file 
						#	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1安装进度: $output_progress%/" $guanjia 2>/dev/null
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1安装进度: $output_progress%/" $guanjia 2>/dev/null
						fi

						current_progress=$output_progress  # 更新当前进度 
					fi
			
					done

					# 等待安装完成
					wait $pid
					if [ $? -ne 0 ]; then
					
					
					echo ""
					echo -e "${RED}error:${NC} 应用安装失败"
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 应用安装失败" >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用安装失败/" $guanjia 2>/dev/null
					echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
					exit 1
					fi
					
					
					# 安装完成后处理文件夹

					echo "安装进度: 100%"
					echo "RPM 包安装完成，开始处理临时文件夹..."
					echo "$(date +"%Y%m%d%H%M%S%3N"):105&100" >> $status_file
					echo "$(date +"%Y%m%d%H%M%S%3N"):107" >> $status_file
					echo "$(date "+%Y-%m-%d %H:%M:%S") RPM 包安装完成，开始处理临时文件夹..." >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1RPM 包安装完成，开始处理临时文件夹/" $guanjia 2>/dev/null
					# 检查并删除同名文件夹
					tmp_folders=$(find $tmp_dir -mindepth 1 -maxdepth 1 -type d)
					for folder in $tmp_folders; do
						# 获取文件夹名称
						folder_name=$(basename "$folder")
						# 构建目标路径
						target_folder="$data_dir/$folder_name"
						
						if [ -d "$target_folder" ]; then
							echo ""
							echo "文件夹 $target_folder 已存在，正在更新..."
							rm -rf "$target_folder"
						fi
						
						echo "复制文件夹 $folder 到 $data_dir"
						echo "$(date "+%Y-%m-%d %H:%M:%S") 复制文件夹 $folder 到 $data_dir" >> $log_file
						echo ""
						cp -r "$folder" "$data_dir"
						if [ $? -eq 0 ]; then
							echo "应用安装成功"
							echo "$(date "+%Y-%m-%d %H:%M:%S") 应用安装成功" >> $log_file
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用安装成功/" $guanjia 2>/dev/null
							echo "$(date +"%Y%m%d%H%M%S%3N"):200" >> $status_file
							# 执行启动文件
							# ls "$target_folder/start.sh"
							chmod 777 "$target_folder/start.sh"
							sh "$target_folder/start.sh"
						else
							echo -e "${RED}error:${NC} 复制文件夹 $folder 到 $data_dir 失败"
							echo "$(date "+%Y-%m-%d %H:%M:%S") error: 复制文件夹 $folder 到 $data_dir 失败" >> $log_file
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1复制文件夹 $folder 到 $data_dir 失败/" $guanjia 2>/dev/null
							echo "$(df -h)" >> $log_file
							echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
						fi
					done


				else
					echo -e "${RED}error:${NC} 未发现rpm包"
					echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 未发现rpm包" >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1未发现rpm包/" $guanjia 2>/dev/null
				fi

			fi



			#cpp包安装
			if [[ "$i_output" == *"cpp"* ]]; then
				echo ""
#				echo "cpppppp"
				echo "$(date "+%Y-%m-%d %H:%M:%S") cpppppp" >> $log_file
				echo "$(date +"%Y%m%d%H%M%S%3N"):101" >> $status_file
				echo "$(date +"%Y%m%d%H%M%S%3N"):103" >> $status_file
				
				# 标志变量，用于跟踪文件拷贝是否成功
				all_files_copied=true

				# 源文件夹 ${package_dir}（当作假根的文件夹）
				# 递归查找源文件夹下的所有文件并计算文件数量
				files_to_copy=($(find ${package_dir} -type f))
				total_files=${#files_to_copy[@]}  # 总文件数量
				current_progress=0  # 当前拷贝进度

				# 如果源文件夹中没有文件，直接退出
				if [ $total_files -eq 0 ]; then
					echo -e "${RED}error:${NC} 没有要拷贝的文件"
					echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 没有要拷贝的文件" >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1没有要拷贝的文件/" $guanjia 2>/dev/null
					exit 1
				else
					echo "总共有 $total_files 个文件，开始安装..."
					echo ""
					echo "安装进度: 0%"
					echo "$(date +"%Y%m%d%H%M%S%3N"):105&0" >> $status_file
				fi

				# 遍历源文件夹中的每个文件进行拷贝
				for file_path in "${files_to_copy[@]}"; do
					# 构建真实根目录下的目标文件路径，去除源文件夹前缀
					target_path="${file_path#$package_dir}"
					# 获取目标文件路径中的目录部分（去掉文件名）
					target_dir=$(dirname "$target_path")

					# 如果目标目录不存在，则创建它
					if [ ! -d "$target_dir" ]; then
						mkdir -p "$target_dir"
						if [ $? -eq 0 ]; then
							echo "$(date "+%Y-%m-%d %H:%M:%S") 成功创建目录: $target_dir" >> $log_file							
						else
							echo -e "${RED}error:${NC} 创建目录 $target_dir 失败，请检查权限等相关问题"
							echo "$(date +"%Y%m%d%H%M%S%3N"):509" >> $status_file
							echo "$(date "+%Y-%m-%d %H:%M:%S") error: 创建目录 $target_dir 失败，请检查权限等相关问题" >> $log_file
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1创建目录 $target_dir 失败，请检查权限等相关问题/" $guanjia 2>/dev/null
							all_files_copied=false
						fi
					fi

					# 拷贝文件
					cp "$file_path" "$target_path"
					
					if [ $? -eq 0 ]; then
						echo "成功将 $file_path 拷贝到 $target_path" >> $log_file
					else
						echo -e "${RED}error:${NC} 将 $file_path 拷贝到 $target_path 失败，请检查权限等相关问题"
						echo "$(date +"%Y%m%d%H%M%S%3N"):509" >> $status_file
						echo "$(date "+%Y-%m-%d %H:%M:%S") error: 将 $file_path 拷贝到 $target_path 失败，请检查权限等相关问题" >> $log_file
						sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1将 $file_path 拷贝到 $target_path 失败，请检查权限等相关问题/" $guanjia 2>/dev/null
						# 如果拷贝失败，设置标志为 false
						all_files_copied=false
					fi

					# 更新拷贝进度
					current_progress=$((current_progress + 1))
					progress=$((current_progress * 100 / total_files))  # 计算当前进度百分比

					# 每拷贝 10% 更新一次进度
					if [ $((progress % 5)) -eq 0 ]; then
						echo "安装进度: $progress%"
						# sleep 0.3
						echo "$(date +"%Y%m%d%H%M%S%3N"):105&$progress" >> $status_file
						echo "$(date "+%Y-%m-%d %H:%M:%S") 安装进度: $progress%" >> $log_file
						sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1安装进度: $progress%/" $guanjia 2>/dev/null
					fi
				done
				
	
				# 如果所有文件都成功拷贝，继续执行下一步
				if [ "$all_files_copied" = true ]; then
					echo ""
					# 安装完成后处理文件夹
					echo "文件安装完成，开始处理临时文件夹..."
					echo "$(date +"%Y%m%d%H%M%S%3N"):107" >> $status_file
					echo "$(date "+%Y-%m-%d %H:%M:%S") 文件安装完成，开始处理临时文件夹..." >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1文件安装完成，开始处理临时文件夹/" $guanjia 2>/dev/null
					# 检查并删除date同名文件夹
						# 获取/tmp下的所有文件夹
					tmp_folders=$(find $tmp_dir -mindepth 1 -maxdepth 1 -type d)
					for folder in $tmp_folders; do
						# 获取文件夹名称
						folder_name=$(basename "$folder")
						# 构建目标路径
						target_folder="$data_dir/$folder_name"
						
							if [ -d "$target_folder" ]; then
								echo ""
								echo "文件夹 $target_folder 已存在，正在更新..."
								rm -rf "$target_folder"
							fi
						echo "复制文件夹 $folder 到 $data_dir"
						cp -r "$folder" "$data_dir"
						if [ $? -eq 0 ]; then
							echo ""
							echo "应用安装成功"
							echo "$(date +"%Y%m%d%H%M%S%3N"):200" >> $status_file
							echo "$(date "+%Y-%m-%d %H:%M:%S") 应用安装成功" >> $log_file
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用安装成功/" $guanjia 2>/dev/null
							
							# 执行启动文件
							chmod 777 "$target_folder/start.sh"
							sh "$target_folder/start.sh"
						else
							echo -e "${RED}error:${NC} 复制文件夹 $folder 到 $data_dir 失败"
							echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
							echo "$(date "+%Y-%m-%d %H:%M:%S") error: 复制文件夹 $folder 到 $data_dir 失败" >> $log_file
							sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1复制文件夹 $folder 到 $data_dir 失败/" $guanjia 2>/dev/null
							echo "$(df -h)" >> $log_file
						fi
					done
					
				else
					echo -e "${RED}error:${NC} 应用安装失败"
					echo "$(date +"%Y%m%d%H%M%S%3N"):599" >> $status_file
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 应用安装失败" >> $log_file
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用安装失败/" $guanjia 2>/dev/null
					echo "$(df -h)" >> $log_file
				fi
								
			fi


			if [[ "$i_output" == *"i_type_err"* ]]; then
				echo ""
				echo -e "${RED}error:${NC} 文件类型异常"
				echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
				echo "$(date "+%Y-%m-%d %H:%M:%S") error: 文件类型异常" >> $log_file
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1文件类型异常/" $guanjia 2>/dev/null
			fi

	
		# 判断1为否输出
	else
		echo -e "${RED}error:${NC} $PATH_OR_FILE 不是tar.gz压缩包"
		echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
		# echo $status_file
		# if [ -f $status_file ] ; then
			# echo "$(date +"%Y%m%d%H%M%S%3N"):506" >> $status_file
		# fi
		echo "$(date "+%Y-%m-%d %H:%M:%S") error: $PATH_OR_FILE 不是tar.gz压缩包" >> $log_file
		sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1$PATH_OR_FILE 不是tar.gz压缩包/" $guanjia 2>/dev/null
	fi


##################################################### 卸载功能 #####################################################


elif [ "$UNINSTALL" ] && [ -n "$PATTERN" ]; then
	echo -e "${GREEN}$appm${NC}"
	echo "" >> $log_file
	echo "$appm" >> $log_file
	echo "$(date "+%Y-%m-%d %H:%M:%S")" >> $log_file
	echo "$(date "+%Y-%m-%d %H:%M:%S") 卸载 $PATTERN" >> $log_file
	sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1卸载 $PATTERN/" $guanjia 2>/dev/null
	echo ""
	echo "应用卸载开始"

	# 判断i_type输出
	type="uninstall"
	i_output=$(i_type)
	
	
	# rpmm包卸载
	if [[ "$i_output" == *"rpmm"* ]]; then
	#	echo "rpmmmmm"
		echo "$(date "+%Y-%m-%d %H:%M:%S") rpmmmmm" >> $log_file
		echo ""
		rpm_folder="$data_dir/$PATTERN/package"
	
		# 获取文件夹下所有以.rpm结尾的文件
		rpm_files=("$rpm_folder"/*.rpm)
		total_files=${#rpm_files[@]}  # 计算总文件数量
		current_file=0                # 初始化当前文件计数
		failed_count=0                # 初始化失败计数
		
		# 检查是否有 .rpm 文件
		if [ $total_files -eq 0 ]; then
			echo -e "${RED}error:${NC} 没有找到任何 .rpm 文件"
			echo "$(date "+%Y-%m-%d %H:%M:%S") error: 没有找到任何 .rpm 文件" >> "$log_file"
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1没有找到任何 .rpm 文件/" $guanjia 2>/dev/null
			exit 1
		fi

		echo "总共有 $total_files 个 RPM 包，开始卸载..."
		ls $rpm_folder
		echo ""
		echo "卸载进度: 0%"
		# 遍历每个 .rpm 文件进行卸载
		for rpm_file in "${rpm_files[@]}"; do
			# 获取文件名（不包含路径部分），去除 .rpm 后缀得到软件包名
			package_name=$(basename "$rpm_file" .rpm) 
			echo "$(date "+%Y-%m-%d %H:%M:%S") 正在卸载软件文件: $package_name" >> "$log_file"

			rpm -e --nodeps "$package_name" >> "$log_file" 2>&1
			if [ $? -eq 0 ]; then
				current_file=$((current_file + 1))  # 成功卸载，更新当前文件计数
				echo "$(date "+%Y-%m-%d %H:%M:%S") 卸载成功" >> "$log_file"
				
				# 每卸载 10% 更新一次进度
				progress=$(( (current_file * 100) / total_files ))
				if [ $((progress % 5)) -eq 0 ]; then
					echo "卸载进度: $progress%"
					echo "$(date "+%Y-%m-%d %H:%M:%S") 卸载进度: $progress%" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1卸载进度: $progress%/" $guanjia 2>/dev/null
				fi
				
			else
				echo -e "${RED}error:${NC} 卸载失败"
				echo "$(date "+%Y-%m-%d %H:%M:%S") error: 卸载失败" >> "$log_file"
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1卸载失败/" $guanjia 2>/dev/null
				failed_count=$((failed_count + 1))  # 增加失败计数
#				exit 1  # 卸载失败则退出脚本
			fi
		done
		
			# 如果所有文件都卸载成功
			if [ "$current_file" -eq "$total_files" ]; then
			
				rm -rf "$data_dir/$PATTERN"
				if [[ $? -eq 0 ]]; then
					echo ""
					echo "卸载完成"
					echo "$(date "+%Y-%m-%d %H:%M:%S") 卸载完成" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1卸载完成/" $guanjia 2>/dev/null
				else
					echo -e "${RED}error:${NC} 删除应用源文件 $target_dir 失败."
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 删除应用源文件 $target_dir 失败" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1删除应用源文件 $target_dir 失败/" $guanjia 2>/dev/null
				fi
			else
				echo ""
				echo -e "${RED}error:${NC} $failed_count 个 RPM 包卸载失败"
				echo "$(date "+%Y-%m-%d %H:%M:%S") error: $failed_count 个 RPM 包卸载失败" >> "$log_file"
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1$failed_count 个 RPM 包卸载失败/" $guanjia 2>/dev/null
			fi
	
	fi
		
	
	#cpp包卸载
	if [[ "$i_output" == *"cpp"* ]]; then
	#	echo "cpppppp"
		echo "$(date "+%Y-%m-%d %H:%M:%S") cpppppp" >> $log_file
		echo ""
		
		cp_folder="$data_dir/$PATTERN/package"
		# 查找所有待删除的文件
		files=($(find "$cp_folder" -type f))
		total_files=${#files[@]}  # 获取文件数量
		current_file=0            # 初始化当前删除的文件计数
		failed_count=0            # 初始化失败计数

		if [ $total_files -eq 0 ]; then
			echo -e "${RED}error:${NC} 没有找到待删除的文件"
			echo "$(date "+%Y-%m-%d %H:%M:%S") error: 没有找到待删除的文件" >> "$log_file"
			sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1没有找到待删除的文件/" $guanjia 2>/dev/null
		else
			echo "总共有 $total_files 个文件，开始删除..." >> "$log_file"
			find "$cp_folder" -type f >> "$log_file"
			echo "$(date "+%Y-%m-%d %H:%M:%S")" >> "$log_file"
			echo "总共有 $total_files 个文件，开始删除..."
			find "$cp_folder" -type f
			echo ""
			echo "卸载进度: 0%"
			# 遍历文件并删除
			for file in "${files[@]}"; do
				# 获取相对路径，去掉前缀
				relative_path=$(echo "/$file" | sed "s|$cp_folder/||")
						
				# 检查文件是否存在
				if [ ! -e "$relative_path" ]; then
					echo -e "${RED}error:${NC} 文件不存在，无法删除： $relative_path"
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 文件不存在，无法删除： $relative_path" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1文件不存在，无法删除： $relative_path/" $guanjia 2>/dev/null
					failed_count=$((failed_count + 1))  # 增加失败计数
					continue  # 跳过删除该文件
				fi

				echo "$(date "+%Y-%m-%d %H:%M:%S") 正在删除软件文件: $relative_path" >> "$log_file"
					
				# 删除文件
				rm -f "$relative_path"
					
				if [ $? -eq 0 ]; then
					current_file=$((current_file + 1))  # 更新当前删除文件计数
					echo "$(date "+%Y-%m-%d %H:%M:%S") 删除成功" >> "$log_file"
						
					# 每删除 1% 更新一次进度
					progress=$(( (current_file * 100) / total_files ))
					if [ $((progress % 5)) -eq 0 ]; then
						echo "删除进度: $progress%"
						echo "$(date "+%Y-%m-%d %H:%M:%S") 删除进度: $progress%" >> "$log_file"
						sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1删除进度: $progress%/" $guanjia 2>/dev/null
					fi
						
				else
					echo -e "${RED}error:${NC} 删除失败"
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 删除失败" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1删除失败/" $guanjia 2>/dev/null
					failed_count=$((failed_count + 1))  # 增加失败计数
				fi
			done
			
		
				# 如果所有文件都删除成功
			if [ "$current_file" -eq "$total_files" ]; then
			
				rm -rf "$data_dir/$PATTERN"
				if [[ $? -eq 0 ]]; then
					echo ""
					echo "卸载完成"
					echo "$(date "+%Y-%m-%d %H:%M:%S") 卸载完成" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1删除完成/" $guanjia 2>/dev/null
				else
					echo -e "${RED}error:${NC} 删除应用源文件 $target_dir 失败"
					echo "$(date "+%Y-%m-%d %H:%M:%S") error: 删除应用源文件 $target_dir 失败" >> "$log_file"
					sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1删除应用源文件 $target_dir 失败/" $guanjia 2>/dev/null
				fi
			else
				echo ""
				echo -e "${RED}error:${NC} $failed_count 个文件卸载失败"
				echo "$(date "+%Y-%m-%d %H:%M:%S") error: $failed_count 个文件卸载失败" >> "$log_file"
				sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1$failed_count 个文件卸载失败/" $guanjia 2>/dev/null
			fi
			
		fi
	
	fi


	if [[ "$i_output" == *"i_type_err"* ]]; then
		echo -e "${RED}error:${NC} 应用源文件 $data_dir/$PATTERN 异常，无法卸载应用"
		echo "$(date "+%Y-%m-%d %H:%M:%S") error: 应用源文件 data_dir/$PATTERN 异常，无法卸载应用" >> $log_file
		sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1应用源文件 data_dir/$PATTERN 异常，无法卸载应用/" $guanjia 2>/dev/null
	fi
	
	if [[ "$i_output" == *"uninstall_file_error"* ]]; then
		echo ""
		echo -e "${RED}error:${NC} 卸载失败，请确认应用名是否正确输入，或是否已安装"
		echo "$(date "+%Y-%m-%d %H:%M:%S") error: 卸载失败，请确认应用名是否正确输入，或是否已安装 " >> $log_file
		sed -i "/sys_OTA_status/ s/\([^,]*, \)[^,]*/\1卸载失败，请确认应用名是否正确输入，或是否已安装/" $guanjia 2>/dev/null	
	fi


################################################### -V 获取安装的程序的版本 ########################################################


elif [ "$V_flag" -eq 1 ] && [ -z "$PATTERN" ]; then
echo ""
for dir in "$data_dir"/*/; do
    # 检查是否是目录
    if [[ -d "$dir" ]]; then
        # 获取文件夹名称
        folder_name=$(basename "$dir")
        
        # 检查 version 文件是否存在
        version_file="$dir/.version"
        if [[ -f "$version_file" ]]; then
            # 查找包含 "版本号" 的行
            version_line=$(grep "版本号" "$version_file")
            if [[ -n "$version_line" ]]; then
                # 输出文件夹名字和版本信息
                echo -e "$folder_name\t$version_line"
            else
                echo -e "$folder_name\tversion信息异常"
            fi
        else
            echo -e "$folder_name\tversion文件异常"
        fi
    fi
done
echo ""


	
elif [ "$V_flag" -eq 1 ] && [ -n "$PATTERN" ]; then
echo ""

	# 检查 $data_dir 是否存在
	if [[ ! -d "$data_dir" ]]; then
		echo "目录 $data_dir 不存在."
		exit 1
	fi

	# 构建完整的文件夹路径
	pattern_dir="$data_dir/$PATTERN"

	# 检查是否存在 $PATTERN 文件夹
	if [[ -d "$pattern_dir" ]]; then
		# 检查 version.txt 文件是否存在
		version_file="$pattern_dir/.version"
		if [[ -f "$version_file" ]]; then
			# 输出 .version 的前 9 行
			head -n 11 "$version_file"
		else
			echo "$PATTERN 应用源文件 version 缺失"
		fi
	else
		echo "$PATTERN 应用源文件不存在，请检查应用名是否正确输入"
	fi
echo ""





####################################################### -l 打印安装程序信息 #########################################################


elif [ "$l_flag" -eq 1 ] && [ -z "$PATTERN" ]; then

 echo ""
 ps -e |head -n 1
 # 使用一个数组来存储所有筛选的进程
 processes=""

	# 遍历 $data_dir 中的所有文件夹
	for dir in "$data_dir"/*/; do
		if [[ -d "$dir" ]]; then
			# 获取文件夹名称，作为关键词
			folder_name=$(basename "$dir")
			
			# 使用 ps -e 和 grep 查找包含该文件夹名称的进程
			process_output=$(ps -e | grep "$folder_name")
			
			# 如果找到了进程，累积到 processes 变量中
			if [[ -n "$process_output" ]]; then
				processes+="$process_output"$'\n'
			fi
		fi
	done

	# 输出所有筛选出的进程
	if [[ -n "$processes" ]]; then
		echo "$processes"
	else
		echo ""
		echo "未查找到应用安装"
		echo ""
	fi



elif [ "$l_flag" -eq 1 ] && [ -n "$PATTERN" ]; then

if [ -d "$data_dir/$PATTERN" ]; then
	result=$(ps -e | grep "$PATTERN" 2>/dev/null)
	# 判断result变量是否为空，如果为空则输出“无”
	if [ -z "$result" ]; then
		echo ""
		echo "应用 $PATTERN 无进程信息"
		echo ""	
		exit 1
	fi
	
	echo ""
    ps -e |head -n 1
	ps -e |grep "$PATTERN"
	echo ""
else
	echo ""
	echo "请确认应用名是否正确输入，或是否已安装 $PATTERN"
	echo ""
fi





##################################################### 参数解析失败 #####################################################


else
	echo "参数不完整或命令有误，请检查参数后重试"
fi
